﻿using System;
using System.Collections;
using System.Linq;
using Microsoft.SharePoint;
using Repo.DataAccess;

namespace Repo.DataCaching
{
    public static class CacheChecker
    {
        public static IList CheckForCachedItems(Type type, string key)
        {
            if (SPContext.Current != null && SPContext.Current.Site != null)
            {
                //Check to see if the CacheReseter has added a value for this key. If the key is content type only (no unique list) then ensure that the cache is still reset
                foreach (var allPropertyKey in
                    SPContext.Current.Web.Site.RootWeb.AllProperties.Keys.Cast<object>().Where(allPropertyKey => allPropertyKey.ToString().StartsWith(key)))
                {
                    var listFromkey = KeyGenerator.GetListFromKey(key);
                    var listFromProperty = KeyGenerator.GetListFromKey(allPropertyKey.ToString());
                    if (string.IsNullOrEmpty(listFromkey) || listFromkey == listFromProperty)
                    {
                        var dtResetCheck = SPContext.Current.Web.Site.RootWeb.AllProperties[allPropertyKey];
                        if (dtResetCheck != null)
                        {
                            var forceReset = LastUpdatedCache.CacheNeedsReseting((DateTime)dtResetCheck, key);
                            if (forceReset && !CurrentlyUpdatingCache.IsCurrentlyUpdating(key))
                            {
                                CurrentlyUpdatingCache.SaveUpdatingTime(key);
                                return null;
                            }
                        }
                    }
                }
            }
            return Cacher.GetFromCache<IList>(key);
        }
    }
}
